// 通用CRUD操作混入
import axios from '../axios/axiosHelper';

export default {
  data() {
    return {
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      searchForm: {
        field: '',
        code: ''
      },
      dialogVisible: false,
      dialogTitle: ''
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    // 获取数据 - 需要在组件中重写
    async fetchData() {
      if (!this.apiEndpoint) {
        console.error('请在组件中定义 apiEndpoint');
        return;
      }
      
      this.loading = true;
      try {
        const params = {
          offset: (this.currentPage - 1) * this.pageSize,
          limit: this.pageSize
        };
        
        // 添加搜索条件
        if (this.searchForm.code) {
          if (this.searchFields) {
            params.field = this.searchFields;
          }
          params.code = this.searchForm.code;
        }
        
        const response = await axios.get(`${this.apiEndpoint}/list`, { params });
        this.tableData = response.data.rows;
        this.total = response.data.total;
      } catch (error) {
        console.error(`获取${this.entityName}数据失败:`, error);
        this.$message.error(`获取${this.entityName}数据失败`);
      } finally {
        this.loading = false;
      }
    },
    
    // 处理页码变化
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    
    // 处理每页显示数量变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchData();
    },
    
    // 打开添加对话框
    handleAdd() {
      this.dialogTitle = `添加${this.entityName}`;
      this.form = this.getDefaultForm();
      this.dialogVisible = true;
    },
    
    // 编辑
    handleEdit(index, row) {
      this.dialogTitle = `编辑${this.entityName}`;
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true;
    },
    
    // 提交表单
    async submitForm(formData) {
      if (!this.apiEndpoint) {
        console.error('请在组件中定义 apiEndpoint');
        return;
      }
      
      this.loading = true;
      try {
        const data = JSON.parse(JSON.stringify(formData || this.form));
        
        // 处理日期格式
        if (data.regis_date && data.regis_date instanceof Date) {
          data.regis_date = data.regis_date.toISOString().slice(0, 19).replace('T', ' ');
        } else if (data.regis_date && typeof data.regis_date === 'string' && data.regis_date.includes('T')) {
          data.regis_date = data.regis_date.slice(0, 19).replace('T', ' ');
        }
        
        if (this.isEditMode(data)) {
          // 更新
          await axios.put(`${this.apiEndpoint}/update`, data);
          this.$message.success('更新成功');
        } else {
          // 添加
          await axios.post(`${this.apiEndpoint}/add`, data);
          this.$message.success('添加成功');
        }
        
        this.dialogVisible = false;
        this.fetchData();
      } catch (error) {
        console.error(`${this.isEditMode(formData || this.form) ? '更新' : '添加'}${this.entityName}失败:`, error);
        
        // 详细错误处理
        let errorMessage = `${this.isEditMode(formData || this.form) ? '更新' : '添加'}${this.entityName}失败`;
        
        if (error.response) {
          const status = error.response.status;
          const responseData = error.response.data;
          
          switch (status) {
            case 400:
              if (responseData && responseData.message) {
                errorMessage = responseData.message;
              } else if (responseData && typeof responseData === 'string' && responseData.includes('Duplicate')) {
                errorMessage = '用户名已存在，请更换';
              } else {
                errorMessage = '请求参数错误，请检查输入信息';
              }
              break;
            case 409:
              errorMessage = '数据冲突，用户名已存在';
              break;
            case 422:
              errorMessage = '数据验证失败，请检查输入格式';
              break;
            case 500:
              errorMessage = '服务器内部错误，请稍后重试';
              break;
            default:
              errorMessage = `${errorMessage}（错误代码：${status}）`;
          }
        } else if (error.request) {
          errorMessage = '网络连接失败，请检查网络连接';
        }
        
        this.$message.error(errorMessage);
      } finally {
        this.loading = false;
      }
    },
    
    // 删除
    async handleDelete(index, row) {
      if (!this.apiEndpoint) {
        console.error('请在组件中定义 apiEndpoint');
        return;
      }
      
      try {
        await this.$confirm(`确认删除该${this.entityName}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        this.loading = true;
        const deleteId = this.getDeleteId(row);
        await axios.delete(`${this.apiEndpoint}/delete/${deleteId}`);
        this.$message.success('删除成功');
        this.fetchData();
      } catch (error) {
        if (error !== 'cancel') {
          console.error(`删除${this.entityName}失败:`, error);
          this.$message.error(`删除${this.entityName}失败`);
        } else {
          this.$message.info('已取消删除');
        }
      } finally {
        this.loading = false;
      }
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchData();
    },
    
    // 判断是否为编辑模式 - 可在组件中重写
    isEditMode(data) {
      return !!(data.id || data.user_no);
    },
    
    // 获取删除ID - 可在组件中重写
    getDeleteId(row) {
      return row.id || row.user_no;
    },
    
    // 获取默认表单数据 - 需要在组件中重写
    getDefaultForm() {
      console.warn('请在组件中重写 getDefaultForm 方法');
      return {};
    }
  }
};